package cn.wolfcode.web.modules.linkman.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;


import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 张创佳
 * @since 2023-09-21
 */
@Controller
@RequestMapping("linkman")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;
    @Autowired
    private ITbCustomerService customerService; //引用企业客户业务类

    private static final String LogModule = "TbCustLinkman";


    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {

        //查出我们的所有企业客户
        List<TbCustomer> list = customerService.list();
        //返回到我们的页面上
        mv.addObject("custs", list);

        mv.setViewName("user/linkman/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        //查出我们的所有企业客户
        List<TbCustomer> list = customerService.list();
        //返回到我们的页面上
        mv.addObject("custs", list);

        mv.setViewName("user/linkman/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        //查出我们的所有企业客户
        List<TbCustomer> list = customerService.list();
        //返回到我们的页面上
        mv.addObject("custs", list);
        mv.setViewName("user/linkman/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('user:linkman:list')")
    public ResponseEntity page(LayuiPage layuiPage, String parameterName, String custId) {

        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        System.out.println("所属企业id" + custId);

        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        //entityService.page(page);
        page = entityService.lambdaQuery().
                eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId) //所属企业
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getLinkman, parameterName) //联系人
                .or()
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getPhone, parameterName) //电话
                .page(page);


        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustLinkman entity, HttpSession session) {

        entity.setInputTime(LocalDateTime.now());

        SysUser sysUser = (SysUser)session.getAttribute(LoginForm.LOGIN_USER_KEY);

        entity.setInputUser(sysUser.getUserId());
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('user:linkman:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }


    /**
     * 导出
     *
     * @param parameterName
     * @param custId
     */
    @SysLog(value = LogModules.DELETE, module = LogModule)
    @RequestMapping("export")
    public void export(HttpServletResponse response, String parameterName, String custId) {
        System.out.println("导出的参数1" + parameterName);
        System.out.println("导出的参数1" + custId);

        //要把什么数据导出到表格当中
        List<TbCustLinkman> list = entityService.lambdaQuery().
                eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId) //所属企业
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getLinkman, parameterName) //联系人
                .or()
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getPhone, parameterName)//电话
                .list();

        //执行文件导出 准备工作
        ExportParams exportParams = new ExportParams();
        /**
         * 参数一： 样式
         * 参数二：导出的实体类的字节码  实际上来解析我们的导出的注释列的
         * 参数三：导出的内容
         */
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbCustLinkman.class, list);
        //导出
        try {
            PoiExportHelper.exportExcel(response, "联系人管理", workbook);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

}
